import { Router } from 'express';
import { MongoClient } from 'mongodb';

const router = Router();

// MongoDB 配置
const mongoUrl = 'mongodb://localhost:27017';
const dbName = 'risk_backend';
const collectionName = 'company_scores';

// 风险企业数据
router.get('/', async (req, res) => {
  const client = new MongoClient(mongoUrl);
  try {
    await client.connect();
    const db = client.db(dbName);
    const collection = db.collection(collectionName);

    // 获取所有公司最新时间段的数据
    const latestData = await collection
      .aggregate([
        {
          $sort: { LComNm: 1, InfoPubDate: -1 }, // 按公司名称升序，时间降序排序
        },
        {
          $group: {
            _id: '$LComNm', // 按公司名称分组
            latestRecord: { $first: '$$ROOT' }, // 获取每组的最新记录
          },
        },
        {
          $replaceRoot: { newRoot: '$latestRecord' }, // 替换根为最新记录
        },
      ])
      .toArray();

    // 统计风险等级
    let lowRiskCount = 0;
    let mediumRiskCount = 0;
    let highRiskCount = 0;

    const riskEnterprises = latestData
      .filter((company) => company.RiskLevel !== '潜在增长') // 忽略 "潜在增长"
      .map((company) => {
        if (company.RiskLevel === '低风险') {
          lowRiskCount++;
        } else if (company.RiskLevel === '中风险') {
          mediumRiskCount++;
        } else if (company.RiskLevel === '高风险') {
          highRiskCount++;
        }

        return {
          name: company.LComNm,
          riskLevel: company.RiskLevel,
          riskReason: company.RiskScore, // 将示例原因替换为 RiskScore
        };
      });

    // 返回结果
    res.json({
      riskLevels: [
        { value: highRiskCount, name: '高' },
        { value: mediumRiskCount, name: '中' },
        { value: lowRiskCount, name: '低' },
      ],
      riskEnterprises,
    });
  } catch (error: any) {
    res.status(500).json({ message: '获取风险数据失败', error: error.message });
  } finally {
    await client.close();
  }
});

export default router;